package conchmusic.conchmusicclient.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;

import java.util.List;

import conchmusic.conchmusicclient.R;
import conchmusic.conchmusicclient.dao.ClientControl;
import conchmusic.conchmusicclient.dao.MyDBHelp;
import conchmusic.conchmusicclient.pojo.Song;
import conchmusic.conchmusicclient.pojo.SongList;
import conchmusic.conchmusicclient.pojo.UpdatedData;
import conchmusic.conchmusicclient.popupWindow.PlayPopup;
import conchmusic.conchmusicclient.popupWindow.SongOperatePopup;
import conchmusic.conchmusicclient.thread.OnlineThread;
import conchmusic.conchmusicclient.util.DeleteSong;
import conchmusic.conchmusicclient.util.DeleteSongInListCommand;
import conchmusic.conchmusicclient.util.FindAllSlistCommand;
import conchmusic.conchmusicclient.util.InitPlayBar;
import conchmusic.conchmusicclient.util.Invoker;
import conchmusic.conchmusicclient.util.JsonParser;
import conchmusic.conchmusicclient.view.PlayBar;

public class SongsActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
    private SongOperatePopup songOperatePopup;
    private int localSongId;
    private int pos;
    private ListView lv_songs;
    private List<Song> list_songs;
    private ClientControl clientControl;
    private int songListId;
    private int userId;
    private MyDBHelp myDBHelp;
    private ImageButton btn_search;
    private SwipeRefreshLayout mSwipeLayout;
    private int songId;
    private Invoker invoker;
    private JsonParser jsonParser;
    private FindAllSlistCommand findAllSlistCommand;
    private DeleteSongInListCommand deleteSongInListCommand;
    private InitPlayBar initPlayBar;
    private List<SongList> songLists;
    private String songListName;
    private DeleteSong deleteSong;

    //音乐播放
    private PlayBar playBar;
    private boolean isOnStart;
    private Intent intent2;
    private Intent intent3;
    private String[] list;
    private Button btn_play;
    private List<Song> downloadSongs;
    private int b;
    int c;
    int d;
    private String[] downloads;
    private PlayPopup playPopup;
    private boolean isDownload;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;

//                Intent upIntent = NavUtils.getParentActivityIntent(this);
//                if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
//                    TaskStackBuilder.create(this)
//                            .addNextIntentWithParentStack(upIntent)
//                            .startActivities();
//                } else {
//                    upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                    NavUtils.navigateUpTo(this, upIntent);
//                }

//            default:
//                return super.onOptionsItemSelected(item);
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_songs);

        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.id_swipe_ly);
        mSwipeLayout.setOnRefreshListener(this);

        btn_play=(Button)findViewById(R.id.playbar_play);
        playBar=(PlayBar)findViewById(R.id.listMusic_playbar);
        btn_search=(ImageButton)findViewById(R.id.btn_search);
        btn_search.setOnClickListener(new onClickListener());


        Bundle bundle=new Bundle();
        Intent intent=getIntent();
        bundle=intent.getExtras();
        songListId=bundle.getInt("slist");


        lv_songs = (ListView) findViewById(R.id.id_songs);

        listShow();

        songLists=clientControl.getSongLists(userId);
        for(int i=0;i<songLists.size();i++){
            if(songLists.get(i).getSongListId()==songListId){
                songListName=songLists.get(i).getSongListName();
            }
        }
        setTitle(songListName);
        isOnStart=true;
        list=new String[list_songs.size()];

        for(int i=0;i<list_songs.size();i++){
            list[i]=Integer.toString(list_songs.get(i).getLocalSongId());
        }





        //点击歌曲

        lv_songs.setOnItemClickListener(new ListView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                downloadSongs=clientControl.findSongs(2);

                downloads=new String[downloadSongs.size()];
                for(int x=0;x<downloadSongs.size();x++){
                    downloads[x]=Integer.toString(downloadSongs.get(x).getLocalSongId());
                }

                Toast.makeText(SongsActivity.this, "我是歌曲 " + list_songs.get(i).getTitle(), Toast.LENGTH_SHORT).show();
                c=0;
                b=0;
                for(int a=0;a<downloadSongs.size();a++){

                    if(downloadSongs.get(a).getSongId()==list_songs.get(i).getSongId()){
                        b=a;
                        break;
                    }else {
                        c=c+1;
                    }
                }
                Log.i("........... "+c,"..."+downloadSongs.size());
                if(c<downloadSongs.size()){
                    Log.i("本地播放","...。。。"+b);
                    String id1=Integer.toString(downloadSongs.get(b).getSongId());
                    String id2=Integer.toString(list_songs.get(i).getSongId());
                    Log.i("下载歌曲ID是"+id1,"歌单中歌曲ID是"+id2);
                    initPlayBar.itemInitPlaybar();
                    intent2=playMusicDirect(b,downloads);
                    btn_play.setBackgroundResource(R.mipmap.ic_pause);
                    startService(intent2);
                }else {
                    d=i;
                    showPlayDialog();
                }

            }

        });

        invoker=new Invoker();

    }



    public void listShow(){
        myDBHelp = new MyDBHelp(SongsActivity.this, "demon", null, 1);
        clientControl=new ClientControl(myDBHelp);
        userId=clientControl.Login().getUserId();
        list_songs=clientControl.findSongs(songListId);
        MySongAdapter sadapter = new MySongAdapter(list_songs);
        lv_songs.setAdapter(sadapter);
    }

    private static final int REFRESH_COMPLETE = 0;
    private static final int REFRESH_FAIL =1;
    private static final int DELETE_COMPLETE=2;
    private static final int DELETE_FAIL=3;
    private static final int DOWNLOAD_SUCCESS=4;
    private static final int DOWNLOAD_FAIL=5;

    private Handler refreshHandler = new Handler() {
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case REFRESH_COMPLETE:

                    mSwipeLayout.setRefreshing(false);
                    listShow();
                    Toast.makeText(SongsActivity.this,"更新成功",Toast.LENGTH_SHORT).show();
                    break;

                case REFRESH_FAIL:

                    mSwipeLayout.setRefreshing(false);
                    Toast.makeText(SongsActivity.this,"网络链接错误",Toast.LENGTH_SHORT).show();
                    break;

                case DOWNLOAD_SUCCESS:

                    Toast.makeText(SongsActivity.this,"下载成功",Toast.LENGTH_SHORT).show();
                    break;

                case DOWNLOAD_FAIL:

                    Toast.makeText(SongsActivity.this,"下载失败",Toast.LENGTH_SHORT).show();
                    break;


                case DELETE_COMPLETE:

                    Toast.makeText(SongsActivity.this,"删除成功",Toast.LENGTH_SHORT).show();
                    onRefresh();

                    break;

                case DELETE_FAIL:

                    Toast.makeText(SongsActivity.this,"网络链接错误",Toast.LENGTH_SHORT).show();
                    break;

            }
        }

    };



    @Override
    protected void onResume() {
        super.onResume();
        if(isOnStart){
            isOnStart=false;
        }else {
//            initAdapter();
        }
        playBar.startMsgReceiver();
        initPlayBar=new InitPlayBar(playBar,this);
        initPlayBar.initPlaybar();

    }

    //一些对话框

    public void showSongMoreDialog() {
        songOperatePopup = new SongOperatePopup(this, R.style.AppTheme, new onClickListener());
        songOperatePopup.show();
    }

    public void showPlayDialog(){
        playPopup = new PlayPopup(this,R.style.AppTheme,new onClickListener());
        playPopup.show();
    }


    //下拉刷新
    @Override
    public void onRefresh() {

        new Thread() {
            @Override
            public void run() {
                try {
                    updateSongList();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        }.start();

    }


    //远程删除歌曲
    public void delete(final int slistid, final int sid){
        new Thread(){
            @Override
            public void run(){
                deleteSongInListCommand=new DeleteSongInListCommand(getResources(),sid,slistid);
                invoker.setTransferCommand(deleteSongInListCommand);
                String getResultJson=invoker.action();
                jsonParser=new JsonParser();
                String onlineGetMsg="";
                try {
                    String type=jsonParser.typeOf(getResultJson);
                    if(type.equals("validInfo")){

                        onlineGetMsg=jsonParser.parseValidInfo(getResultJson);
                        Log.i("。。。。。。。。。","删除歌单Id="+slistid+"中的歌曲Id="+sid);
                        refreshHandler.sendEmptyMessage(DELETE_COMPLETE);

                    }else if(type.equals("invalidInfo")){

                        onlineGetMsg=jsonParser.parseInvalidInfo(getResultJson);
                        Log.i("invalidInfo",onlineGetMsg);
                        refreshHandler.sendEmptyMessage(DELETE_FAIL);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        }.start();
    }

    //远程更新歌单

    private void updateSongList() throws JSONException {

        findAllSlistCommand = new FindAllSlistCommand(getResources(), userId);
        invoker.setTransferCommand(findAllSlistCommand);
        String jsonRecive = invoker.action();

        Log.i("下载的信息为",jsonRecive);

        jsonParser=new JsonParser();
        if(jsonParser.typeOf(jsonRecive).equals("invalidInfo")){

            Log.i("updateSongInvalidInfo",jsonParser.parseInvalidInfo(jsonRecive));
            refreshHandler.sendEmptyMessage(REFRESH_FAIL);

        }else {

            UpdatedData ud = jsonParser.parseUpdatedData(jsonRecive);
            clientControl.update(ud);
            refreshHandler.sendEmptyMessage(REFRESH_COMPLETE);

        }
    }


    class onClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            downloadSongs=clientControl.findSongs(2);

            localSongId=getPos();
            for(int a=0;a<list_songs.size();a++){
                if(list_songs.get(a).getLocalSongId()==localSongId){
                    songId=list_songs.get(a).getSongId();
                }
            }

            isDownload=false;
            for(int b=0;b<downloadSongs.size();b++) {

                if (downloadSongs.get(b).getSongId() == songId) {
                    isDownload = true;

                }
            }

            switch (v.getId()) {

                case R.id.btn_search:

                    EditText ET=(EditText)findViewById(R.id.et_songname);
                    String searchSongName=ET.getText().toString().trim();

                    List<Song> searchResult=clientControl.findSongs(songListId,searchSongName);

                    MySongAdapter sadapter = new MySongAdapter(searchResult);
                    lv_songs.setAdapter(sadapter);
                    break;

                case R.id.id_addtoOther:

                    Intent intent2=new Intent(SongsActivity.this,AddtoOtherList.class);
                    intent2.putExtra("songListId2",songListId);
                    intent2.putExtra("userId2",userId);
                    intent2.putExtra("songId",songId);
                    startActivity(intent2);
                    songOperatePopup.cancel();
                    break;

                case R.id.id_download:


                    if(isDownload){
                        Toast.makeText(SongsActivity.this,"已存在",Toast.LENGTH_SHORT).show();
                    }else {
                        Song download=clientControl.findSong(localSongId);
                        OnlineThread onlineThread=new OnlineThread(download,SongsActivity.this,refreshHandler);
                        Thread thread=new Thread(onlineThread);
                        thread.start();

                    }


                    songOperatePopup.cancel();

                    break;

                case R.id.id_rm:

                    delete(songListId,songId);

                    songOperatePopup.cancel();

                    break;

                case R.id.id_rm_and_dlt:


                    if(isDownload){

                        deleteSong=new DeleteSong(clientControl.findSong(localSongId).getLocalSongUrl(),clientControl.findSong(localSongId).getLocalPictureUrl(),clientControl.findSong(localSongId).getLocalLyricUrl());
                        deleteSong.deleteSong();

                    }

                    delete(songListId,songId);
                    clientControl.deleteOriginSong(localSongId,songListId);
                    songOperatePopup.cancel();


                    break;

                case R.id.songcancel:

                    songOperatePopup.cancel();
                    break;

                case R.id.id_playsure:

                    playPopup.cancel();
                    Log.i("在线播放","。。。。。"+d);
                    initPlayBar.itemInitPlaybar();
                    intent3=playMusic(d,list);
                    btn_play.setBackgroundResource(R.mipmap.ic_pause);
                    startService(intent3);

                    break;

                case R.id.id_playcancel:

                    playPopup.cancel();

                    break;
            }
        }
    }


    public int getPos() {
        return pos;
    }


    public class MySongAdapter extends BaseAdapter implements View.OnClickListener {
        private Context context;
        private List<Song> data;
        public MySongAdapter(List<Song> data){
            this.data = data;
        }

        @Override
        public int getCount() {
            return data == null ? 0 : data.size();
        }

        @Override
        public Object getItem(int i) {
            return data.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder = null;

            if(context == null) {
                context = viewGroup.getContext();
            }

            if(view == null){
                view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item,null);
                viewHolder = new ViewHolder();
                viewHolder.mTv = (TextView)view.findViewById(R.id.mTv);
                viewHolder.aTv=(TextView)view.findViewById(R.id.aTv);
                viewHolder.mBtn = (ImageButton)view.findViewById(R.id.mBtn);
                view.setTag(viewHolder);
            }
            viewHolder = (ViewHolder)view.getTag();
            //设置tag标记
            viewHolder.mBtn.setTag(R.id.btn,data.get(i).getLocalSongId());
            viewHolder.mBtn.setOnClickListener(this);
            viewHolder.mTv.setText(data.get(i).getTitle());
            viewHolder.aTv.setText(data.get(i).getArtistNames().get(0));
            return view;
        }

        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.mBtn:
                    int b = (int) view.getTag(R.id.btn);
                    showSongMoreDialog();
                    pos=b;
                    break;

//                case R.id.mTv:
//                    int t = (int)view.getTag(R.id.tv);
//                    Toast.makeText(context,"我是歌曲" + t,Toast.LENGTH_SHORT).show();
//                    break;
            }
        }

        class ViewHolder{
            TextView mTv;
            TextView aTv;
            ImageButton mBtn;
        }
    }
    @Override
    protected void onPause() {

        super.onPause();
        playBar.closeMsgReceiver();
    }

    @Override
    protected void onStop() {

        super.onStop();
        this.finish();
    }

    public Intent playMusic(int position, String[] list){
        Intent intent=new Intent();
        intent.putExtra("action","play");
        intent.putExtra("posit",position);
        intent.putExtra("songList",list);
        intent.setAction("music2");
        intent.setPackage(SongsActivity.this.getPackageName());
        return intent;
    }

    public Intent playMusicDirect(int position,String[] list){
        Intent intent=new Intent();
        intent.putExtra("action","playDirect");
        intent.putExtra("posit",position);
        intent.putExtra("songList",list);
        intent.setAction("music2");
        intent.setPackage(SongsActivity.this.getPackageName());
        return intent;
    }

}

